import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns, ProCoreActionType } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import {
  ArrayCards,
  ArrayCollapse,
  ArrayItems,
  ArrayTable,
  Cascader,
  DatePicker,
  Editable,
  FormDialog,
  FormItem,
  FormLayout,
  FormTab,
  Input,
  NumberPicker,
  Select,
} from '@formily/antd-v5';
import { createSchemaField, ISchema } from '@formily/react';
import React, { ReactNode } from 'react';
import { createForm, onFieldValueChange } from '@formily/core';
import PictureWall from '@/components/picturewall';
import { genId, importFrom1688 } from '@/services/product';
import useSpinning from '@/uses/useSpinning';
import { createRequest } from '@/uses/useCurdPage';
import { useDrawerForm } from '@/uses/useForm';
import { useProTable } from '@/uses/useProTable';


type DetailInfo = {
  id: string;
};
const emptyDetailInfo: DetailInfo = {
  id: '',
}

const SchemaField = createSchemaField({
  components: {
      FormItem,
      Input,
      NumberPicker,
      FormTab,
      ArrayItems,
      Select,
      DatePicker,
      Space,
      ArrayCards,
      ArrayTable,
      ArrayCollapse,
      Cascader,
      PictureWall,
      Editable,
      FormLayout,
  },
})
const form = createForm({
  effects() {
    onFieldValueChange('attrList.*', (field) => {
      let attrList = field.query('attrList').get('value')

      // 如果 attrList 为空，则不进行任何操作
      if (!attrList || attrList.length === 0) {
        return;
      }

      // 处理属性
      form.setFieldState(field.query('attrList'), async (state) => {
        // 如果 value 为空，则不处理
        if (!state.value || state.value.length === 0) {
          return;
        }
        // 如果 value 中最后一项的 ID 未设置或者等于 0，则设置为当前时间戳
        if (!state.value[state.value.length - 1].id || state.value[state.value.length - 1].id === 0) {
          const id = await genId();
          console.log('id', id);
          state.value[state.value.length - 1].id = id;
        }
      })

      // 处理选项
      form.setFieldState(field.query('attrList.*.optionList'), async (state) => {
        // 如果 value 为空，则不处理
        if (!state.value || state.value.length === 0) {
          return;
        }
        // 如果 value 中最后一项的 ID 未设置或者等于 0，则设置为当前时间戳
        if (!state.value[state.value.length - 1].id || state.value[state.value.length - 1].id === 0) {
          state.value[state.value.length - 1].id = await genId();
        }
      })
      
      // [{name, optionList}]
      // [{name, optionId}]: name 为属性名称+属性选项名，optionId 为属性选项 ID
      const skuValues = attrList.reduce(
        (prev:any, {name, optionList}:any) => {
          if (prev.length === 0) {
            return optionList.map((option:any) => ({name: name + ':' + option.name, optionIds: [option.id]}));
          }
          return prev.flatMap(
            (prevItem:any) => 
              optionList.map((option:any) => 
                {return {name: prevItem.name + ", " + name + ':' + option.name, optionIds: prevItem.optionIds.concat([option.id])}}
            )
          )
        }, []
      )
      console.log("sssss:", skuValues)
      form.setFieldState(field.query('skuList'), (state) => {
        state.value = skuValues
      })
    })
  },
})
const formTab = FormTab.createFormTab()

const schema = {
  type: 'object',
  properties: {
    collapse: {
      type: 'void',
      'x-component': 'FormTab',
      'x-component-props': {
        formTab: '{{formTab}}',
      },
      properties: {
        tab1: {
          type: 'void',
          'x-component': 'FormTab.TabPane',
          'x-component-props': {
            tab: '基础信息',
          },
          properties: {
            name: {
              type: 'string',
              title: '产品名称',
              required: true,
              'x-decorator': 'FormItem',
              'x-component': 'Input',
            },
            basePrice: {
              title: '基础价格',
              type: 'string',
              'x-decorator': 'FormItem',
              'x-component': 'NumberPicker',
            },
            unit: {
              title: '单位',
              type: 'string',
              'x-decorator': 'FormItem',
              'x-component': 'Input',
            },
            mainImageList: {
              type: 'array',
              title: '产品主图',
              'x-decorator': 'FormItem',
              'x-component': 'PictureWall',
            },
            intro: {
              type: 'string',
              title: '详情',
              'x-decorator': 'FormItem',
              'x-component': 'Input.TextArea',
            },
            specDetail: {
              type: 'string',
              title: '产品参数',
              'x-decorator': 'FormItem',
              'x-component': 'Input.TextArea',
            },
          },
        },
        tab2: {
          type: 'void',
          'x-component': 'FormTab.TabPane',
          'x-component-props': {
            tab: '产品属性',
          },
          properties: {
            attrList: {
              type: 'array',
              required: true,
              title: '属性',
              'x-decorator': 'FormItem',
              'x-component': 'ArrayItems',
              items: {
                type: 'object',
                'x-component': 'ArrayItems.Item',
                properties: {
                  sort: {
                    type: 'void',
                    'x-decorator': 'FormItem',
                    'x-component': 'ArrayItems.SortHandle',
                  },
                  popover: {
                    type: 'void',
                    title: '完善属性信息',
                    'x-decorator': 'Editable.Popover',
                    'x-component': 'FormLayout',
                    'x-component-props': {
                      layout: 'vertical',
                    },
                    'x-reactions': [
                      {
                        fulfill: {
                          schema: {
                            title: '{{$self.query(".name").value() }}',
                          },
                        },
                      },
                    ],
                    properties: {
                      name: {
                        type: 'string',
                        title: '属性名称',
                        required: true,
                        'x-decorator': 'FormItem',
                        'x-component': 'Input',
                        'x-component-props': {
                          style: {
                            width: 300,
                          },
                        },
                      },
                      optionList: {
                        type: 'array',
                        required: true,
                        'x-component': 'ArrayItems',
                        'x-decorator': 'FormItem',
                        title: '选项列表',
                        items: {
                          type: 'object',
                          properties: {
                            space: {
                              type: 'void',
                              'x-component': 'Space',
                              properties: {
                                sort: {
                                  type: 'void',
                                  'x-decorator': 'FormItem',
                                  'x-component': 'ArrayItems.SortHandle',
                                },
                                name: {
                                  type: 'string',
                                  'x-decorator': 'FormItem',
                                  'x-component': 'Input',
                                },
                                remove: {
                                  type: 'void',
                                  'x-decorator': 'FormItem',
                                  'x-component': 'ArrayItems.Remove',
                                },
                              },
                            },
                          },
                        },
                        properties: {
                          add: {
                            type: 'void',
                            title: '添加条目',
                            'x-component': 'ArrayItems.Addition',
                          },
                        },
                      },
                    }
                  },
                  remove: {
                    type: 'void',
                    'x-decorator': 'FormItem',
                    'x-component': 'ArrayItems.Remove',
                  },
                },
              },
              properties: {
                addition: {
                  type: 'void',
                  title: '新增属性',
                  'x-component': 'ArrayItems.Addition',
                },
              },
            },
            skuList: {
              type: 'array',
              'x-component': 'ArrayCollapse',
              'x-decorator': 'FormItem',
              items: {
                type: 'object',
                'x-component': 'ArrayCollapse.CollapsePanel',
                'x-component-props': {
                  header: 'SKU信息',
                },
                properties: {
                  index: {
                    type: 'void',
                    'x-component': 'ArrayCollapse.Index',
                  },
                  name: {
                    type: 'string',
                    'x-decorator': 'FormItem',
                    title: 'sku',
                    required: true,
                    'x-disabled': true,
                    'x-component': 'Input',
                  },
                  price: {
                    type: 'string',
                    'x-decorator': 'FormItem',
                    title: '价格',
                    required: true,
                    'x-component': 'NumberPicker',
                  },
                  picList: {
                    type: 'array',
                    title: '产品图片',
                    'x-decorator': 'FormItem',
                    'x-component': 'PictureWall',
                  },
                  remove: {
                    type: 'void',
                    'x-component': 'ArrayCollapse.Remove',
                  },
                  moveUp: {
                    type: 'void',
                    'x-component': 'ArrayCollapse.MoveUp',
                  },
                  moveDown: {
                    type: 'void',
                    'x-component': 'ArrayCollapse.MoveDown',
                  },
                },
              },
            },
          },
        },
      },
    },
  },
}

const import1688Schema = {
  type: 'object',
  properties: {
    url: {
      type: 'string',
      title: '1688 URL',
      required: true,
      'x-decorator': 'FormItem',
      'x-component': 'Input',
      'x-component-props': { placeholder: '请输入1688链接' },
    },
  },
}

const showFormDialog = (title: string, schema:ISchema, handler: (values: any) => any) => {
  const dialog =  FormDialog(title, () => {
    return (
      <FormLayout labelCol={6} wrapperCol={10}>
        <SchemaField schema={schema} />
      </FormLayout>
    )
  })
  dialog.open().then(handler)
  return dialog
}

const customCols: ProColumns<DetailInfo>[] = [
  {
    title: 'SPU',
    dataIndex: 'id',
    copyable: true,
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
  {
    title: '品名',
    dataIndex: 'name',
    copyable: true,
    ellipsis: true,
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
];

const tableTitle = '产品管理';

export default () => {
  const { SpinDom, show, hide } = useSpinning({title: '加载中...'});

  const {deleteRequest, detailRequest, listRequest, saveRequest} = createRequest({resourceName: 'products'});
  const {showForm} = useDrawerForm({form, schema, saveRequest, detailRequest, emptyDetailInfo, scope: {formTab}});

  const {TableElement, actionRef} = useProTable({
    tableTitle,
    customCols,
    listRequest,
    operationRender: (dom: ReactNode, record: DetailInfo, index: number, action: ProCoreActionType | undefined) => [
      <Button size='small' key='edit' onClick={() => showForm(record.id, async () => await action?.reload())}>查看</Button>,
      <Button size='small' key='del' danger={true} onClick={async () => await deleteRequest(record.id)}>删除</Button>,
    ],
    toolBarRender: () => [
      <FormDialog.Portal key="import1688">
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={async () => {
            showFormDialog("自动爬取1688", import1688Schema, async ({url}: {url: string}) => {
              if (!url.startsWith('https://detail.1688.com/')) {
                return message.error('URL不合法');
              }
              show(30 * 1000)
              const response = await window.electronAPI.wdioRunner(url)
              await importFrom1688(response)
              hide()
            })
          }}
          type="primary"
        >
          1688导入
        </Button>
      </FormDialog.Portal>,
      <Button
        key="button"
        icon={<PlusOutlined />}
        onClick={async () => {
          await showForm(null, async () => await actionRef.current?.reload());
        }}
        type="primary"
      >
        新增
      </Button>,
    ]
  });

  return (
    <PageContainer
      header={{title: tableTitle}}
    >
      <TableElement/>
      <SpinDom/>
    </PageContainer>
  );
};